package com.gan.bi.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author gbw
 * @date 2023/7/13
 * Excel 工具类
 */
@Slf4j
public class ExcelUtils {

    /**
     * Excel 转 CSV
     *
     * @param file
     */
    public static String excelToCSV(MultipartFile file) {
        // 使用 EasyExcel 来将 Excel 文件读取为 Map 形式
        List<Map<Integer, String>> list = null;
        try {
            // 要将 MultipartFile 类型的文件转换成输入流才能读取
            list = EasyExcel.read(file.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.error("表格转换错误!");
        }
        if (CollectionUtils.isEmpty(list)) {
            return "";
        }
        // 转为 CSV
        StringBuilder res = new StringBuilder();
        // 读取表头,过滤掉为空的表头
        LinkedHashMap<Integer, String> title = (LinkedHashMap) list.get(0);
        List<String> head = title.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
        res.append(StringUtils.join(head,",")).append("/n");
        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer, String> data = (LinkedHashMap<Integer, String>) list.get(i);
            res.append(StringUtils.join(data.values(),",")).append("/n");
        }
        return res.toString();
    }

    public static void main(String[] args) {
        excelToCSV(null);
    }
}
